#include "driver/touch_pad.h"
#include "esp_log.h"

#define TAG "Touch pad driver"

#define TOUCH_THRESH_NO_USE (0)
#define TOUCHPAD_FILTER_TOUCH_PERIOD (10)

static void tp_driver_intr_handler(void *arg);
static void tp_driver_set_thresholds(void);

static bool s_pad_activated[TOUCH_PAD_MAX];

/**
 * Initialize touch pad peripheral
 */
void tp_driver_init(void) {
    ESP_LOGI(TAG, "Initializing touch pad");
    ESP_ERROR_CHECK(touch_pad_init());
    touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
    touch_pad_set_voltage(TOUCH_HVOLT_2V7, TOUCH_LVOLT_0V5, TOUCH_HVOLT_ATTEN_1V);

    for (int i = 0; i < TOUCH_PAD_MAX; i++) {
        touch_pad_config(i, TOUCH_THRESH_NO_USE);
    }

    touch_pad_filter_start(TOUCHPAD_FILTER_TOUCH_PERIOD);

    tp_driver_set_thresholds();

    // Register interrupt for TOUCH_PAD_NUM3 (GPIO15)
    // touch_pad_isr_register(tp_driver_intr_handler, NULL);
}

/**
 * Set thresholds for touch pads
 */
void tp_driver_set_thresholds(void) {
    uint16_t touch_value;
    touch_pad_read_filtered(TOUCH_PAD_NUM3, &touch_value);
    ESP_LOGI(TAG, "Touch pad 3 init value: %d", touch_value);
    ESP_ERROR_CHECK(touch_pad_set_thresh(TOUCH_PAD_NUM3, touch_value * 2 / 3));
}

/**
 * Interrupt handler for touch pad 3 (GPIO15)
 */
static void tp_driver_intr_handler(void *arg) {
    uint32_t pad_intr = touch_pad_get_status();
    touch_pad_clear_status();

    if (pad_intr & (1 << TOUCH_PAD_NUM3)) {
        s_pad_activated[TOUCH_PAD_NUM3] = true;
        ESP_LOGI(TAG, "Touch pad 3 (GPIO15) activated!");
    }
}

/**
 * Check if touch pad 3 has been activated
 */
bool tp_driver_is_pad_activated(void) {
    if (s_pad_activated[TOUCH_PAD_NUM3]) {
        s_pad_activated[TOUCH_PAD_NUM3] = false;
        return true;
    }
    return false;
}

void tp_driver_print_touch_pad_value(void) {
    // uint16_t touch_value;
    // // Read the filtered value from TOUCH_PAD_NUM3
    // touch_pad_read_filtered(TOUCH_PAD_NUM3, &touch_value);
    // ESP_LOGI(TAG, "Current value of TOUCH_PAD_NUM3: %d", touch_value);

    uint16_t touch_value;
        touch_pad_read_raw_data(3, &touch_value);
        ESP_LOGI(TAG, "Touch pad %d init value: %d", 3, touch_value);
}